#include "CServer.h"
#include <iostream>
#include "AsioIOServicePool.h"
#include "CSession.h"
#include "UserMgr.h"

CServer::CServer(boost::asio::io_context& io_context,short port)
:_io_context(io_context),_acceptor(io_context,tcp::endpoint(boost::asio::ip::tcp::v4(),port)),_port(port)
{
    Start();
}


CServer::~CServer()
{
    _acceptor.close();
    std::cout<<"CServer::~CServer()"<<std::endl;
}


void CServer::ClearSession(const std::string& session_id)
{   
    if(_sessions.find(session_id) != _sessions.end())
    {
        UserMgr::GetInstance()->RemoveUserSession(_sessions[session_id]->GetUserId());
    }

    {
        std::lock_guard<std::mutex> lock(_sessions_mutex);
        _sessions.erase(session_id);
    }
}

void CServer::Start()
{
    auto& ioc = AsioIOServicePool::GetInstance()->GetIOService();
    std::shared_ptr<CSession> session = std::make_shared<CSession>(ioc,this);
    
    _acceptor.async_accept(session->GetSocket(),std::bind(&CServer::HandleAccept,
                                                        this,session,std::placeholders::_1));
}


void CServer::HandleAccept(std::shared_ptr<CSession> session,
                        const boost::system::error_code& ec)
{
    if (ec)
    {
        std::cout<<"HandleAccept error:"<<ec.message()<<std::endl;
        //this->Start();
        return;
    }
    //没有错误的情况下将session存放到map中
    {
        std::lock_guard<std::mutex> lock(_sessions_mutex);
        _sessions[session->GetSessionId()] = session;

    }
    session->Start();
    this->Start();
    
}
